package com.example.hello.service.impl;

import com.example.hello.mapper.InteractionMapper;
import com.example.hello.pojo.Interaction;
import com.example.hello.service.InteractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InteractionServiceImpl implements InteractionService {

    @Autowired
    private InteractionMapper interactionMapper;

    @Override
    public void markFavorite(Integer userId, Integer bookId) {
        // 先根据 userId, bookId 查找
        Interaction record = interactionMapper.findByUserAndBook(userId, bookId);
        if (record == null) {
            // 不存在则插入
            Interaction newRecord = new Interaction();
            newRecord.setUserId(userId);
            newRecord.setBookId(bookId);
            newRecord.setRating(0.0);
            newRecord.setFavorite(true);
            newRecord.setBorrowCount(0);
            interactionMapper.insertInteraction(newRecord);
        } else {
            // 存在则更新 isFavorite = true
            interactionMapper.updateFavorite(userId, bookId, true);
        }
    }

    @Override
    public void updateOrInsertRating(Integer userId, Integer bookId, double rating) {
        // 先查询当前记录是否存在
        Interaction record = interactionMapper.findByUserAndBook(userId, bookId);
        if (record == null) {
            // 不存在则插入新的记录，设置 rating = 传入参数，isFavorite = false，borrowCount = 0
            Interaction newRecord = new Interaction();
            newRecord.setUserId(userId);
            newRecord.setBookId(bookId);
            newRecord.setRating(rating);
            newRecord.setFavorite(false);
            newRecord.setBorrowCount(0);
            interactionMapper.insertInteraction(newRecord);
        } else {
            // 存在则更新 rating 字段为传入参数
            interactionMapper.updateRating(userId, bookId, rating);
        }
    }

    @Override
    public void borrowBook(Integer userId, Integer bookId) {
        // 根据 userId 和 bookId 查询记录
        Interaction record = interactionMapper.findByUserAndBook(userId, bookId);
        if (record == null) {
            // 若不存在，则插入记录：rating=0, isFavorite=false, borrowCount=1
            Interaction newRecord = new Interaction();
            newRecord.setUserId(userId);
            newRecord.setBookId(bookId);
            newRecord.setRating(0.0);
            newRecord.setFavorite(false);
            newRecord.setBorrowCount(1);
            interactionMapper.insertInteraction(newRecord);
        } else {
            // 存在则更新借阅次数，直接加1更新
            interactionMapper.updateBorrowCount(userId, bookId);
        }
    }

    @Override
    public void cancleFavorite(Integer userId, Integer bookId) {
        interactionMapper.updateFavorite(userId, bookId, false);
    }
}
